package com.xm.utils.httpclient;

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.message.BasicNameValuePair;

import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.StringJoiner;
import java.util.stream.Collectors;

public class HttpRequestUtil {
    /**
     * url必须不携带任何参数
     *
     * @param url
     * @param param
     * @return
     */
    public static HttpGet newGet(String url, Map<String, Object> param) {
        if (param != null && param.size() > 0) {
            StringJoiner joiner = new StringJoiner("&");
            param.entrySet().forEach(e -> joiner.add(e.toString()));
            url = url + "?" + joiner;
        }
        return new HttpGet(url);
    }


    public static HttpPost newJsonPost(String url, Map<String, Object> params) {
        return newJsonPost(url, new JSONObject(params));
    }

    public static HttpPost newJsonPost(String url, JSONObject params) {
        HttpPost post = new HttpPost(url);
        setRequest(post, ContentType.APPLICATION_JSON, new StringEntity(params.toJSONString(), StandardCharsets.UTF_8));
        return post;
    }

    public static HttpPost newFormUrlencodedPost(String url, Map<String, Object> params) {
        HttpPost post = new HttpPost(url);
        List<BasicNameValuePair> collect = params.entrySet()
                .stream()
                .map(e -> new BasicNameValuePair(e.getKey(), e.getValue().toString()))
                .collect(Collectors.toList());
        setRequest(post, ContentType.APPLICATION_FORM_URLENCODED, new UrlEncodedFormEntity(collect, StandardCharsets.UTF_8));
        return post;
    }

    public static HttpPost newXmlPost(String url, String xmlStr) {
        HttpPost post = new HttpPost(url);
        setRequest(post, ContentType.APPLICATION_XML, new StringEntity(xmlStr, StandardCharsets.UTF_8));
        return post;
    }

    public static void setRequest(HttpEntityEnclosingRequest request, ContentType contentType, HttpEntity entity) {
        request.setHeader("Content-Type", contentType.getMimeType());
        request.setHeader("charset", "utf-8");
        request.setEntity(entity);
    }
}
